﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Microsoft.AspNet.SignalR;

namespace TheCup.Hubs
{
    public class Chat : Hub
    {
        const string SYSTEM = "<< System >>";
        static ConcurrentDictionary<string, string> userlist = new ConcurrentDictionary<string, string>();
        static int anonCounter = 1;

        public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
        {
            if (stopCalled)
            {
                Console.WriteLine("stopCalled, do i care?");
            }
            else
            {
                Console.WriteLine("not?!? stopCalled, yaarp!");
            }

            string removedUser = string.Empty;
            if (userlist.TryRemove(Context.ConnectionId, out removedUser))
            {
                Clients.Others.broadcastMessage(SYSTEM, removedUser + " disconnected..");
                Clients.All.updateUserList(userlist.ToArray());
            }

            return base.OnDisconnected(stopCalled);
        }

        public void addUser(string username)
        {
            userlist.TryAdd(Context.ConnectionId, username);
            Clients.All.updateUserList(userlist.ToArray());
            Clients.Others.broadcastMessage(SYSTEM, username + " connected..");
        }

        public void getUsers()
        {
            Clients.Caller.updateUserList(userlist.ToArray());
            var all = Clients.All;
            var temp = "";
        }

        static ConcurrentQueue<string> messages = new ConcurrentQueue<string>();
        
        public void Send(string name, string message)
        {
            if (messages.Count == 100)
            {
                string dequeuedValue;
                messages.TryDequeue(out dequeuedValue);
            }

            messages.Enqueue(string.Join(" : ", name, message));
            Clients.All.broadcastMessage(name, message);
        }

        public void getMessages()
        {
            Clients.Caller.getMessages(messages.ToArray());
        }
    }
}